/*
 *  Copyright © OpenAtom Foundation.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.openatom.ubml.model.common.definition.commonmodel.json.model;


import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
import org.openatom.ubml.model.common.definition.cef.json.CefNames;
import org.openatom.ubml.model.common.definition.cef.json.SerializerUtils;
import org.openatom.ubml.model.common.definition.cef.json.Variable.CommonVariableEntityDeseriazlier;
import org.openatom.ubml.model.common.definition.cef.variable.CommonVariableEntity;
import org.openatom.ubml.model.common.definition.commonmodel.IGspCommonObject;
import org.openatom.ubml.model.common.definition.commonmodel.entity.GspCommonModel;
import org.openatom.ubml.model.common.definition.commonmodel.entity.GspCommonObject;
import org.openatom.ubml.model.common.definition.commonmodel.entity.VersionControlInfo;
import org.openatom.ubml.model.common.definition.commonmodel.json.CommonModelNames;
import org.openatom.ubml.model.common.definition.commonmodel.json.object.CmObjectDeserializer;
import org.openatom.ubml.model.common.definition.commonmodel.util.HandleAssemblyNameUtil;

import static com.fasterxml.jackson.core.JsonToken.FIELD_NAME;

/**
 * The Json Deserializer Of Common Model
 *
 * @ClassName: CommonModelDeserializer
 * @Author: Benjamin Gong
 * @Date: 2021/1/11 17:13
 * @Version: V1.0
 */
public abstract class CommonModelDeserializer extends JsonDeserializer<GspCommonModel> {

    @Override
    public GspCommonModel deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        return deserializeCommonModel(jsonParser);
    }

    public GspCommonModel deserializeCommonModel(JsonParser jsonParser) {
        GspCommonModel model = createCommonModel();
        SerializerUtils.readStartObject(jsonParser);
        while (jsonParser.getCurrentToken() == FIELD_NAME) {
            String propName = SerializerUtils.readPropertyName(jsonParser);
            readPropertyValue(model, propName, jsonParser);
        }
        SerializerUtils.readEndObject(jsonParser);
        afterReadModel(model);
        return model;
    }

    private void afterReadModel(GspCommonModel model) {
        if (model.getVariables() != null) {
            CommonVariableEntity varEntity = model.getVariables();
            varEntity.setName(String.format("%1$s变量", model.getName()));
            varEntity.setCode(String.format("%1$sVariable", model.getCode()));
            varEntity.setParentApiAssemblyInfo(model.getApiNamespace());
            varEntity.setParentCoreAssemblyInfo(model.getCoreAssemblyInfo());
            varEntity.setParentEntityAssemblyInfo(model.getEntityAssemblyInfo());
        }
    }

    private void readPropertyValue(GspCommonModel model, String propName, JsonParser jsonParser) {
        switch (propName) {
            case CommonModelNames.ID:
                model.setID(SerializerUtils.readPropertyValue_String(jsonParser));
                break;
            case CommonModelNames.CODE:
                model.setCode(SerializerUtils.readPropertyValue_String(jsonParser));
                break;
            case CommonModelNames.NAME:
                model.setName(SerializerUtils.readPropertyValue_String(jsonParser));
                break;
            case CommonModelNames.BE_LABEL:
                model.setBeLabel(SerializerUtils.readStringArray(jsonParser));
                break;
            case CommonModelNames.IS_VIRTUAL:
                model.setIsVirtual(SerializerUtils.readPropertyValue_boolean(jsonParser));
                break;
            case CommonModelNames.ENTITY_TYPE:
                model.setEntityType(SerializerUtils.readPropertyValue_String(jsonParser));
                break;
            case CommonModelNames.PRIMAY_KEY_ID:
                SerializerUtils.readPropertyValue_String(jsonParser);
                break;
            case CommonModelNames.MAIN_OBJECT:
                readMainObject(jsonParser, model);
                break;
            case CommonModelNames.VARIABLES:
                readVariables(jsonParser, model);
                break;
            case CommonModelNames.EXTEND_NODE_LIST:
                readExtendNodeList(jsonParser, model);
                break;
            case CommonModelNames.FK_CONSTRAINTS:
                readFkConstraints(jsonParser, model);
                break;
            case CommonModelNames.EXT_PROPERTIES:
                readExtProperties(jsonParser, model);
                break;
            case CommonModelNames.GENERATING_ASSEMBLY:
                String tempValue = SerializerUtils.readPropertyValue_String(jsonParser);
                model.setDotnetGeneratingAssembly(tempValue);
                model.setGeneratingAssembly(handleGeneratingAssembly(tempValue));
                break;
            case CefNames.I18N_RESOURCE_INFO_PREFIX:
                model.setI18nResourceInfoPrefix(SerializerUtils.readPropertyValue_String(jsonParser));
                break;
            case CommonModelNames.IS_USE_NAMESPACE_CONFIG:
                model.setIsUseNamespaceConfig(SerializerUtils.readPropertyValue_boolean(jsonParser));
                break;
            case CommonModelNames.VERSION_CONTROL_INFO:
                model.setVersionContronInfo(readVersionControlInfo(jsonParser));
                break;
            default:
                if (!readExtendModelProperty(model, propName, jsonParser)) {
                    throw new RuntimeException(String.format("GspCommonDataTypeDeserializer未识别的属性名：%1$s", propName));
                }
        }
    }

    private VersionControlInfo readVersionControlInfo(JsonParser jsonParser) {
        VersionControlInfo info = new VersionControlInfo();
        if (SerializerUtils.readNullObject(jsonParser)) {
            return info;
        }
        SerializerUtils.readStartObject(jsonParser);
        SerializerUtils.readPropertyName(jsonParser);
        info.setVersionControlElementId(SerializerUtils.readPropertyValue_String(jsonParser));
        SerializerUtils.readEndObject(jsonParser);
        return info;
    }

    private String handleGeneratingAssembly(String readPropertyValueString) {
        return HandleAssemblyNameUtil.convertToJavaPackageName(readPropertyValueString);
    }

    private void readExtProperties(JsonParser jsonParser, GspCommonModel model) {
        //后端文件没有序列化该属性
    }

    private void readFkConstraints(JsonParser jsonParser, GspCommonModel model) {
        SerializerUtils.readStartArray(jsonParser);
        SerializerUtils.readEndArray(jsonParser);
    }

    private void readExtendNodeList(JsonParser reader, GspCommonModel model) {
        SerializerUtils.readStartArray(reader);
        while (reader.getCurrentToken() == JsonToken.START_OBJECT) {
            SerializerUtils.readStartObject(reader);
            String key = SerializerUtils.readPropertyValue_String(reader);
            String value = SerializerUtils.readPropertyValue_String(reader);
            model.getExtendNodeList().put(key, value);
            SerializerUtils.readEndObject(reader);
        }
        SerializerUtils.readEndArray(reader);
    }

    private void readVariables(JsonParser jsonParser, GspCommonModel model) {
        CommonVariableEntityDeseriazlier deseriazlier = new CommonVariableEntityDeseriazlier();
        CommonVariableEntity entity = (CommonVariableEntity)deseriazlier.deserializeCommonDataType(jsonParser);
        model.setVariables(entity);
    }

    private void readMainObject(JsonParser jsonParser, GspCommonModel model) {
        CmObjectDeserializer deserializer = createCmObjectDeserializer();
        GspCommonObject mainObj = (GspCommonObject)deserializer.deserializeCommonDataType(jsonParser);
        if (mainObj != null) {
            mainObj.setBelongModel(model);
            mainObj.setBelongModelID(model.getID());
            setChildObjedtBelongModel(mainObj, model);
        }
        model.setMainObject(mainObj);
    }

    private void setChildObjedtBelongModel(IGspCommonObject parentObject, GspCommonModel cm) {
        if (parentObject == null || parentObject.getContainChildObjects() == null || parentObject.getContainChildObjects().size() == 0) {
            return;
        }
        for (IGspCommonObject childObject : parentObject.getContainChildObjects()) {
            childObject.setBelongModel(cm);
            childObject.setBelongModelID(cm.getID());
            // 递归
            setChildObjedtBelongModel(childObject, cm);
        }
    }

    protected boolean readExtendModelProperty(GspCommonModel model, String propName, JsonParser jsonParser) {
        return false;
    }

    protected abstract GspCommonModel createCommonModel();

    protected abstract CmObjectDeserializer createCmObjectDeserializer();
}
